{% extends "base.html" %}

{% block title %}用户管理 - 用户管理系统{% endblock %}

{% block content %}
<div class="row">
    <div class="col-12">
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h2><i class="fas fa-users"></i> 用户管理</h2>
            <button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addUserModal">
                <i class="fas fa-plus"></i> 添加用户
            </button>
        </div>
    </div>
</div>

<div class="row">
    <div class="col-12">
        <div class="card">
            <div class="card-header">
                <h5>用户列表</h5>
            </div>
            <div class="card-body">
                <div class="table-responsive">
                    <table class="table table-striped table-hover" id="usersTable">
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>用户名</th>
                                <th>邮箱</th>
                                <th>用户类型</th>
                                <th>状态</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody id="usersTableBody">
                            <!-- 用户数据将通过JavaScript动态加载 -->
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 添加用户模态框 -->
<div class="modal fade" id="addUserModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">添加用户</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="addUserForm">
                    <div class="mb-3">
                        <label class="form-label">用户名</label>
                        <input type="text" class="form-control" name="username" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">邮箱</label>
                        <input type="email" class="form-control" name="email" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">密码</label>
                        <input type="password" class="form-control" name="password" required>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">用户类型</label>
                        <select class="form-select" name="user_type">
                            <option value="1">普通用户</option>
                            <option value="2">管理员</option>
                        </select>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="addUser()">添加</button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
let users = [];

document.addEventListener('DOMContentLoaded', function() {
    loadUsers();
});

async function loadUsers() {
    showLoading(true);
    try {
        // 注意：这里需要你实现获取用户列表的API接口
        // 由于你的代码中没有提供获取用户列表的接口，这里只是示例
        const response = await fetch('/api/users', {
            headers: getAuthHeaders()
        });

        if (response.ok) {
            users = await response.json();
            renderUsersTable();
        } else {
            showAlert('加载用户列表失败', 'danger');
        }
    } catch (error) {
        showAlert('加载用户列表失败: ' + error.message, 'danger');
    } finally {
        showLoading(false);
    }
}

function renderUsersTable() {
    const tbody = document.getElementById('usersTableBody');
    tbody.innerHTML = '';

    users.forEach(user => {
        const row = document.createElement('tr');
        row.innerHTML = `
            <td>${user.id}</td>
            <td>${user.username}</td>
            <td>${user.email}</td>
            <td>${user.user_type === 2 ? '<span class="badge bg-warning">管理员</span>' : '<span class="badge bg-info">普通用户</span>'}</td>
            <td>${user.status === 1 ? '<span class="badge bg-success">正常</span>' : '<span class="badge bg-danger">禁用</span>'}</td>
            <td>
                <button class="btn btn-sm btn-outline-primary" onclick="editUser(${user.id})">
                    <i class="fas fa-edit"></i>
                </button>
                <button class="btn btn-sm btn-outline-danger" onclick="deleteUser(${user.id})">
                    <i class="fas fa-trash"></i>
                </button>
                <button class="btn btn-sm btn-outline-warning" onclick="forceLogout(${user.id})">
                    <i class="fas fa-sign-out-alt"></i>
                </button>
            </td>
        `;
        tbody.appendChild(row);
    });
}

async function addUser() {
    const form = document.getElementById('addUserForm');
    const formData = new FormData(form);

    const userData = {
        username: formData.get('username'),
        email: formData.get('email'),
        password: formData.get('password'),
        user_type: parseInt(formData.get('user_type'))
    };

    showLoading(true);
    try {
        const response = await fetch('/api/addUser', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                ...getAuthHeaders()
            },
            body: JSON.stringify(userData)
        });

        const result = await response.json();

        if (result.success) {
            showAlert('用户添加成功', 'success');
            $('#addUserModal').modal('hide');
            form.reset();
            loadUsers(); // 重新加载用户列表
        } else {
            showAlert('添加失败: ' + result.message, 'danger');
        }
    } catch (error) {
        showAlert('添加失败: ' + error.message, 'danger');
    } finally {
        showLoading(false);
    }
}

function getAuthHeaders() {
    const token = localStorage.getItem('token');
    return {
        'Authorization': `Bearer ${token}`
    };
}

function showAlert(message, type) {
    // 创建alert元素并显示
    const alertDiv = document.createElement('div');
    alertDiv.className = `alert alert-${type} alert-dismissible fade show`;
    alertDiv.innerHTML = `
        ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    `;

    document.querySelector('.container-fluid').prepend(alertDiv);

    // 3秒后自动消失
    setTimeout(() => {
        alertDiv.remove();
    }, 3000);
}
</script>
{% endblock %}